package top.callname.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Properties;

/**
 * 读取数据库配置文件
 * 
 * @author 维康
 *
 */
public class PropertiesUtil {

	private static Properties defaultProperty;

	static void init() {
		// 设置默认参数
		defaultProperty = new Properties();
		defaultProperty.setProperty("jdbc.driverName", "com.mysql.jdbc.Driver");
		defaultProperty.setProperty("jdbc.dbUser", "root");
		defaultProperty.setProperty("jdbc.dbPass", "root");
		String dbProps = "db.properties";
		boolean loaded = (loadProperties(defaultProperty, "."
				+ File.separatorChar + dbProps))
				|| (loadProperties(
						defaultProperty,
						PropertiesUtil.class.getResourceAsStream("/WEB-INF/"
								+ dbProps)))
				|| (loadProperties(defaultProperty, PropertiesUtil.class
						.getClassLoader().getResourceAsStream(dbProps)));
		if (!loaded)
			System.out.println("初始化错误:没有加载到db.properties属性文件!");
	}

	private static boolean loadProperties(Properties props, String path) {
		try {
			File file = new File(path);
			if ((file.exists()) && (file.isFile())) {
				props.load(new FileInputStream(file));
				return true;
			}
		} catch (IOException ignore) {
			ignore.printStackTrace();
		}
		return false;
	}

	private static boolean loadProperties(Properties props, InputStream is) {
		try {
			if (is != null) {
				props.load(is);
				return true;
			}
		} catch (IOException ignore) {
			ignore.printStackTrace();
		}
		return false;
	}

	public static String getDriverName() {
		return getProperty("jdbc.driverName");
	}

	public static String getDbUser() {
		return getProperty("jdbc.dbUser");
	}

	public static String getDbPass() {
		return getProperty("jdbc.dbPass");
	}

	public static String getDbUrl() {
		return getProperty("jdbc.dbUrl");
	}

	public static String getHostUrl() {
		return getProperty("host.url");
	}
	
	public static String getProperty(String name) {
		return getProperty(name, null);
	}

	public static String getProperty(String name, String fallbackValue) {
		String value;
		try {
			value = System.getProperty(name, null);
			if (null == value) {
				value = defaultProperty.getProperty(name, fallbackValue);
			}
		} catch (AccessControlException ace) {
			value = fallbackValue;
		}
		return value;
	}

	static {
		init();
	}
}
